<template>
  <div class="login-body">
    <div class="login-box">
      <div class="login-box-side">
        <div class="logo">Store</div>
        <div class="comments">基于Thinkphp6、vue3 + ts + vite 的通用商城开发。</div>
        <div class="comments">测试账号密码：test 123456</div>
        <div class="comments">注明：该网站只是演示系统功能作用</div>
        <div class="footer">粤ICP备2023012653号 ©&nbsp;frank&nbsp;</div>
      </div>
      <div class="login-box-form">
        <div class="system-name">
          {{systemInfo?.system_name || '系统名称'}} <span class="ctitle">{{systemInfo?.system_version || '0.01'}}</span>
        </div>
        <div class="title">管理员登录</div>
        <div class="ctitle">ADMIN USER LOGIN</div>
        <el-form
          class="mt30"
          ref="loginRef"
          :model="loginForm"
          :rules="loginRules"
        >
          <el-form-item prop="account">
            <el-input
              class="login-main-form-item"
              v-model="loginForm.account"
              placeholder="请输入账号"
              size="large"
              maxlength="11"
              prefix-icon="UserFilled"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              type="password"
              size="large"
              :showPassword="true"
              prefix-icon="Lock"
            >
            </el-input>
          </el-form-item>

          <el-form-item prop="captcha_code">
            <el-input
              v-model="loginForm.captcha_code"
              placeholder="请输入图形验证码"
              type="text"
              size="large"
              maxlength="4"
              prefix-icon="Picture"
            >
              <template #suffix>
                <div
                  v-if="captchaImage"
                  @click="toLoginCaptcha"
                  class="login-captcha-img"
                >
                  <img :src="captchaImage" />
                </div>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              class="login-btn"
              type="primary"
              size="large"
              @click="toLogin(loginRef)"
              :loading="loginLoad"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, reactive, onMounted } from "vue";
import { useAdmin, useMenus,useConfig} from "@/store";
import { useRouter } from "vue-router";
import { login, getLoginCaptcha } from "@/api/common";
import type { FormInstance } from "element-plus";
import type { Result,ResultError } from "@/types";
import system from "@/router/modules/system";

const { proxy } = getCurrentInstance() as any

const {
  proxy: { $message, $notice, $utils },
} = getCurrentInstance() as any;

const configStore = useConfig();

const systemInfo = configStore.getSystemInfo;

const adminStore = useAdmin();

const MenusStore = useMenus();

const router = useRouter();

const loginForm = reactive({
  account: "",
  password: "",
  captcha_uniqid: "",
  captcha_code: "",
});

const loginRules = reactive({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha_code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const loginRef = ref<HTMLElement>();

const loginLoad = ref<boolean>(false);

const toLogin = async (formEl:typeof FormInstance | undefined) => {
  if (!formEl) return;
  if (loginLoad.value == true) {
    return;
  }
  formEl.validate((valid:any) => {
    if (valid) {
      loginLoad.value = true;
      login(loginForm)
        .then(async (res:Result) => {
          adminStore.setAdmin(res.data.user_info);
          adminStore.setToken(res.data.token, res.data.expires_time);
          MenusStore.setMenus(res.data.menus.menusList);
          MenusStore.setPermissionAction(res.data.menus.action);
          $notice({
            title: "登录成功",
            message: "正在进入系统...",
            type: "success",
            onClose: () => {
              let path: any = res.data.menus.homePath || "/";
              if (router.currentRoute.value.query.redirect) {
                path = router.currentRoute.value.query.redirect;
              }
              router.push({
                path: path,
              });
            },
          });
        })
        .catch((err:ResultError) => {
          loginLoad.value = false;
          if (err.data?.code == 701) {
            loginForm.captcha_code = "";
            toLoginCaptcha();
          }
          $utils.errorMsg(err);
        });
    }
  });
};
const captchaImage = ref<string>("");

const toLoginCaptcha = () => {
  getLoginCaptcha()
    .then((res) => {
      captchaImage.value = res.data.data;
      loginForm.captcha_uniqid = res.data.uniqid;
    })
    .catch((error) => {
      $utils.errorMsg(error);
    });
};

const keydownEvent = () => {
  document.onkeydown = (e: any) => {
    if (e.defaultPrevented) {
      return;
    }
    if (e.keyCode === 13) {
      toLogin(proxy?.$refs['loginRef']);
    }
  };
};

onMounted(() => {
  toLoginCaptcha();
  keydownEvent();
});
</script>
<style scoped lang="scss">
.login-body {
  background: #f6f8f9;
}
.login-box {
  width: 1000px;
  height: 600px;
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  z-index: 1;
  -webkit-box-shadow: 0px 20px 80px 0px rgb(0 0 0 / 30%);
  box-shadow: 0px 20px 80px 0px rgb(0 0 0 / 30%);
}
.login-box-side,
.login-box-form {
  position: relative;
  width: 50%;
  padding: 80px 80px 48px;
}
.login-box-side {
  background: #282c34;
}
.login-box-side::after,
.login-box-side::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
.login-box-side::after {
  background: url(@/theme/image/login/login_after.png) no-repeat right bottom;
}
.login-box-side::before {
  background: url(@/theme/image/login/login_before.png) no-repeat 0 0;
}
.login-box-side .logo {
  color: #fff;
  font-size: 20px;
}
.login-box-side .comments {
  color: #fff;
  font-size: 14px;
  margin-top: 60px;
  line-height: 1.8;
}
.login-box-side .footer {
  position: absolute;
  bottom: 50px;
  font-size: 14px;
  padding-top: 40px;
  z-index: 2;
  color: #fff;
}
.login-box-form .system-name{
  color: #282c34;
  font-size: 24px;
  margin-bottom: 20px;
}
.login-box-form .title {
  color: #282c34;
  font-size: 16px;
}
.login-box-form .ctitle {
  color: #c4c4c4;
  font-size: 12px;
  margin-top: 10px;
}

.login-btn {
  width: 100%;
}
.login-captcha-img img {
  width: 80px;
  text-align: center;
  cursor: pointer;
  user-select: none;
  display: block;
}
</style>